# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2024-09-05 16:07
# @Function :
from datetime import datetime
import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX
from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor

from common.constant import ACTIVE_PARAGRAPHS, START_TIME


def set_font(paragraph, font_name, font_size, bold=False):
    """
    设置段落字体和大小
    """
    # 设置字体和大小
    for run in paragraph.runs:
        run.font.name = font_name
        run.font.size = Pt(font_size)
        run.font.bold = bold
        # run.font.color.rgb = RGBColor(255, 0, 0)
        run.element.rPr.rFonts.set(qn('w:eastAsia'), font_name)


def add_hyperlink(paragraph, text, url):
    # 获取paragraph的part对象，并且创建一个新的关系
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # 创建 w:hyperlink 标签并且添加所需的值
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # 创建一个 w:r 元素 和一个 w:rPr 元素
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # 把所有的 xml 元素合并到一起，并且添加显示的文本给 w:r 元素
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # 创建一个新的 Run 对象并且添加新的超链接进去
    r = paragraph.add_run()
    r._r.append(hyperlink)

    # 设置超链接的样式，样式颜色为超链接，并且文本有下划线
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink


def simplify_content(content_data: list):
    filtered_content = [s.strip() for s in content_data if s.strip()]
    if len(filtered_content) > ACTIVE_PARAGRAPHS:
        filtered_content = filtered_content[:ACTIVE_PARAGRAPHS]
        filtered_content[-1] = filtered_content[-1] + '...'
    return filtered_content


def generate_number():
    start_date = START_TIME
    current_date = datetime.now()
    delta = current_date - start_date
    period = (delta.days // 7) + 1
    return period
